package net.web.belerofont.action.support;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.web.belerofont.action.Action;
import net.web.belerofont.action.Interceptor;
import net.web.belerofont.action.Invoker;
import net.web.belerofont.action.InvokerContext;
import net.web.belerofont.action.URIMap;

public class InvokerSupport implements Invoker {
	private InvokerContext context;
	private Action action;
	private List<Interceptor> list;

	private InvokerSupport() {

	}

	public Action getAction() {
		return this.context.getAction();
	}

	public static Invoker instance(InvokerContext context,
			LinkedList<Interceptor> list) {
		InvokerSupport invoke = new InvokerSupport();
		invoke.context = context;
		invoke.list = list;
		return invoke;
	}

	public URIMap invoke() {
		if (!list.isEmpty()) {
			Interceptor interceptor = list.get(0);
			list.remove(0);
			
			return interceptor.intercept(this);
		} else {
			Action action = context.getAction();
			HttpServletRequest request = context.getHttpRequest();
			HttpServletResponse response = context.getHttpResponse();
			return action.execute(request, response);
		}

	}

	public InvokerContext getContext() {
		return context;
	}
}
